package com.ezscript.print;
public class Spiral {
	public static void main(String[] args) {
		int m = 8;
		int n = 5;
		int[][] arr = getArr(m,n);
		printArr(arr);
		System.out.println("---------------------");
		arr = getSqureArr(m);
		printArr(arr);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public static int[][] getSqureArr(int len){
		return getArr(len,len);
	}
	
	public static int[][] getArr(int m,int n){
		int total = m * n;
		int [][] arr = new int[n][m];
		int count = 1;

		int x = 0;
		int y = 0;
		
		int tempCount = 0;
		int turn = 1;

		while (count <= total) {
			switch (turn) {
				case 1:
					arr[y][x++] = count;
					if(++tempCount == m){
						tempCount =0;
						turn++;
						x--;
						y++;
					}
					break;
				case 2:
					arr[y++][x] = count;
					if(++tempCount == (n-1)){
						tempCount =0;
						turn++;
						y--;
						x--;
					}
					break;
				case 3:
					arr[y][x--] = count;
					if(++tempCount == (m-1)){
						tempCount =0;
						turn++;
						x++;
						y--;
					}
					break;
				case 4:
					arr[y--][x] = count;
					if(++tempCount == (n-2)){
						tempCount =0;
						turn = 1;
						y++;
						x++;
						n -= 2;
						m -=2;
					}
					break;
			}//end switch
			count++;
		}//end while
		return arr;
		
	}

	private static void printArr(int[][] arr) {
		for(int i = 0 ;i< arr.length ; i++){
			for(int j=0; j<arr[i].length; j++){
				System.out.print(arr[i][j]+"\t");
			}
			System.out.println();
		}
		
	}
}
